<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单操作类 wmsHandler
 * @package  	htdocs
 * @subpackage  module/base
 * @create by allen.qiang
 * @version 	1.0  
 */

class wmsHandler {

    private $dbca;

    private $eai;

    public function __construct( &$dbca, &$eai = null ) {
        $this->dbca = $dbca;
        if (!is_null($eai)){
            $this->eai = $eai;
        }
    }
    
	/**
     * 查询仓库信息
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchStore( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //仓库ID
        if(isset($arg_array['storeID']) && is_numeric($arg_array['storeID'])){
            $sql .= ' AND storeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['storeID'];
        }

        //仓库名称
        if (isset($arg_array['storeName']) && !empty($arg_array['storeName'])) {
            $sql .= ' AND storeName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['storeName'];
        }

        //仓库编号
        if (isset($arg_array['storeNo']) && !empty($arg_array['storeNo'])) {
            $sql .= ' AND storeNo = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['storeNo'];
        }

        //创建人
        if(isset($arg_array['creator']) && !empty($arg_array['creator']) ){
            $sql .= ' AND creator LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['creator']) . '%';
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wms_store ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wms_store ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array) {
                return null;
            }

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'storeID' 	=> $item->storeID,
                    'storeName' => $item->storeName,
                    'storeNo' 	=> $item->storeNo,
                    'address' 	=> $item->address,
                    'linkman' 	=> $item->linkman,
                    'mobile' 	=> $item->mobile,
                    'phone' 	=> $item->phone,
                    'isdefault' => $item->isdefault,
                    'description' => $item->description
                );

            }

            return $item_array;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }

    }
	
    /**
     * 下载订单修改商品库存数量
     * @param unknown $data	
     * @return multitype:string number |multitype:string NULL
     */
    public function updateStorage($data){
    	if(!isset($data['goodsID'], $data['storeID'] , $data['amount'] , $data['operator'])){
    		return array('code' => 400 , 'message' => '参数错误') ;
    	}
    	
    	$goodsID = $data['goodsID'];			//商品号
    	$storeID = $data['storeID'];			//仓库号
    	$amount	 = $data['amount'];				//数量
    	$operator= $data['operator'];			//操作人
    	$enableSaleAmount = 0 ;					//可售数量
    	$lockAmount	= 0 ;						//锁定数量
    	
    	$this->dbca->beginTransaction();
    	
    	try{
    		//修改商品库存
    		$this->dbca->stmt_query('UPDATE wms_goodsstore SET enableSaleAmount=enableSaleAmount-?,timeStamp=NOW(),lockAmount=lockAmount+? WHERE storeID=? AND goodsID=?','iiii',$amount,$amount,$storeID,$goodsID);
    		
    		//判断数量是否小于0
    		$goodsstore = new entity('wms_goodsstore');
    		$goodsstore->storeID = $storeID;
    		$goodsstore->goodsID = $goodsID;
    		if($this->dbca->fetch($goodsstore)){
    			$enableSaleAmount = $goodsstore->enableSaleAmount;
    			$lockAmount	= $goodsstore->lockAmount;
    		}
    		if($enableSaleAmount < 0){
    			throw new Exception(sprintf('商品号「%s」的库存不足' , $goodsID), 404);
    		}
    		
    		//加入库存修改日志
    		$obj_store_log = new entity('log_goodsstore');
    		$obj_store_log->goodsID = $goodsID;
    		$obj_store_log->storeID = $storeID;
    		$obj_store_log->creator = $operator;
    		$obj_store_log->oldEnableSaleAmount = $enableSaleAmount + $amount;
    		$obj_store_log->newEnableSaleAmount = $enableSaleAmount;
    		$obj_store_log->oldLockAmount = $lockAmount- $amount;
    		$obj_store_log->newLockAmount = $lockAmount;
    		$this->dbca->save($obj_store_log , 'wms');

    		$this->dbca->commit();
    		return array('message'=>'库存更新成功' , 'code'=>200 );
    	}catch (Exception $e){
    		$this->dbca->rollBack();
    		error_log($e->getMessage());
    		return array('message'=>'系统错误，更新失败','code'=>$e->getCode() );
    	}
    
    }
    
}